import { strip, joinArr, filterArr, readJson, writeJson } from '../common/utils.js'
import _ from 'lodash'

const hold = (x: string) => {
  return x === '-' ? undefined : x
}

const splitTimeRange = (timeRange: any) => {
  if (timeRange == null) {
    return {}
  }
  let startTime = undefined
  let endTime = undefined
  if (timeRange.includes('至')) {
    const parts = timeRange.split('至');
    startTime = parts[0] ? parts[0].trim() : ''
    endTime = parts[1] ? parts[1].trim() : ''
  } else {
    console.log('只提供了一个时间，无法确定是开始还是结束时间。')
  }
  startTime = startTime === '-' ? undefined : startTime
  endTime = endTime === '-' ? undefined : endTime
  return { startTime: startTime || undefined , endTime: endTime || undefined }
}

const setup = async () => {
  const json = readJson('companys')
  const data = JSON.parse(json).map((k: any) => {
    let projects: any = undefined
    if (!_.isEmpty(k.project)) {
      if (_.isArray(k.project.img)) {
        projects = k.project.img.map((k: any, i: number) => {
          return {
            img: k,
            desc: strip(k.project?.desc[i]) || undefined
          }
        })
      } else {
        projects = [
          {
            img: k.project?.img,
            desc: strip(k.project?.desc) || undefined
          }
        ]
      }
    }
    let manager: any = undefined
    if (!_.isEmpty(k.manager)) {
      if (_.isArray(k.manager.img)) {
        manager = k.manager.img.map((k: any, i: number) => {
          return {
            img: k,
            name: k.manager?.name[i] || undefined,
            job: k.manager?.job[i] || undefined,
            desc: strip(k.manager?.desc[i]) || undefined
          }
        })
      } else {
        manager = [
          {
            img: k.manager?.img || undefined,
            name: k.manager?.name || undefined,
            job: k.manager?.job || undefined,
            desc: strip(k.manager?.desc) || undefined
          }
        ]
      }
    }
    const desc = filterArr(k.desc)
    const { startTime, endTime } = splitTimeRange(k.businessTime)
    return {
      jId: k.jId,
      name: k.name,
      time: k.time,
      type: k.type,
      status: k.status,
      money: k.money,
      location: k.location,
      businessStartTime: startTime,
      businessEndTime: endTime,
      beloneLocation: k.beloneLocation,
      creditCode: k.creditCode,
      checkTime: k.checkTime,
      oldName: hold(k.oldName),
      orang: k.orang,
      industry: hold(k.industry),
      scope: k.scope,
      pics: k.pics || undefined,
      manager: manager || undefined,
      desc: desc.length === 0 ? undefined : desc,
      workItems: joinArr(k.workItems),
      talentsList: joinArr(k.talentsList),
      workTime: joinArr(k.workTime),
      projects: projects
    }
  })
  
  const _json = JSON.stringify(data, null, 2)
  
  writeJson('companys_v2', _json)
}

export default setup